package helpers;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import debugs.IpAddressDebug;

import entities.Domain;
import entities.IpAddress;

public class CrawlerHelper {
	public static IpAddress getIp(String ip) {
		IpAddress ipAddress = new IpAddress();
		
		String url = "http://www.statscrop.com/ip/?ip=" + ip;
		
		try {
			Document doc = Jsoup.connect(url).get();
			
			Elements ipInfo = doc.select("#content .attributes ");
			
			String countryCode = ipInfo.select("dd:eq(1)").html();
			String countryCode3 = ipInfo.select("dd:eq(3)").html();
			String countryName = ipInfo.select("dd:eq(5)").html();
			String city = ipInfo.select("dd:eq(7)").html();
			String continentCode = ipInfo.select("dd:eq(9)").html();
			String latitude = ipInfo.select("dd:eq(11)").html();
			latitude = convertGeo(latitude);
			String longitude = ipInfo.select("dd:eq(13)").html();
			longitude = convertGeo(longitude);
			
			String whoisIp = doc.select("#innercontent2 > div").eq(2).html();
			
			ipAddress.setIp(ip);
			ipAddress.setCountryCode(countryCode);
			ipAddress.setCountryCode3(countryCode3);
			ipAddress.setCountryName(countryName);
			ipAddress.setCity(city);
			ipAddress.setContinentCode(continentCode);
			ipAddress.setLatitude(latitude);
			ipAddress.setLongitude(longitude);
			ipAddress.setWhoisIp(whoisIp);
			
			
		} catch (Exception e) {
			ipAddress = null;
		}
		
		return ipAddress;
	}
	
	public static Domain getDomainIp(String name) {
		Domain domain = new Domain();
		try {
			String url = "http://www.nearby.org.uk/api/dig.php?l=" + name;
			Document doc = Jsoup.connect(url).get();
			String ip = doc.text();
			domain.setDomain(name);
			domain.setIp(ip);
		} catch (Exception e) {
			domain = null;
		}
		return domain;
	}
	
	private static String convertGeo(String geo) {
		geo = geo.replace("&deg;", ".").replace("'", "").replace("\"", "");
		geo = geo.replaceAll("[^0-9.]", "");
		return geo;
	}
	
}
